//
//  CalculatorBrain.swift
//  ToDo
//
//  Created by yanhangpu on 2021/7/7.
//

import Foundation
import UIKit

enum CalculatorBrain {
    /// 键入数字
    case left(String)
    /// 键入数字、操作符
    case leftOperation (
            left: String,
            operation: CalculatorButtonItem.Operation
         )
    /// 键入数字、操作符、数字
    case leftOperationRight (
            left: String,
            operation: CalculatorButtonItem.Operation,
            right: String
         )
    /// 出错
    case error
    
    var formatter: NumberFormatter {
        let f = NumberFormatter()
        f.minimumFractionDigits = 0
        f.maximumFractionDigits = 8
        return f
    }
    
    var output: String {
        let result: String
        switch self {
        case .left(let left):
            result = left
        case .leftOperation(left: let left, operation: _):
            result = left
        case .leftOperationRight(left: let left, operation: _, right: _):
            result = left
        case .error:
            result = "Error"
        }
        guard Double(result) != nil else {
            return "Error"
        }
        return result
    }
    
    
    func applyDot() -> CalculatorBrain {
        return self
    }
    
    func applyCommand(command: CalculatorButtonItem) -> CalculatorBrain {
        return self
    }
    
    func applyOperation(operation: CalculatorButtonItem) -> CalculatorBrain {
        return self
    }
    
    func applyDigit(digit: CalculatorButtonItem) -> CalculatorBrain {
        return self
    }
    
    func apply(item: CalculatorButtonItem) -> CalculatorBrain {
        
        switch item {
        case .command(_):
            return applyCommand(command: item)
        case .digit(_):
            return applyDigit(digit: item)
        case .dot:
            return applyDot()
        case .operation:
            return applyOperation(operation: item)
        }
    }
}


